package com.cicadasmall.common.utils;

import com.cicadasmall.common.base.LoginUser;
import lombok.experimental.UtilityClass;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;

import java.util.Optional;


/**
 * SecurityUtils
 *
 * @author Jin
 */
@UtilityClass
public class SecurityUtils {

    /**
     * 获取当前登录的用户
     *
     * @return
     */
    public static LoginUser getCurrentLoginUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = null;
        if (authentication instanceof OAuth2Authentication) {
            OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) authentication;
            if (!"client_credentials".equals(oAuth2Authentication.getOAuth2Request().getGrantType())) {
                loginUser = (LoginUser) oAuth2Authentication.getUserAuthentication().getPrincipal();
            }
        } else if (authentication instanceof UsernamePasswordAuthenticationToken) {
            Object object = authentication.getPrincipal();
            if (object instanceof LoginUser) {
                loginUser = (LoginUser) object;
            }
        }
        return loginUser;
    }

    public static Optional<LoginUser> getOptionalCurrentLoginUser() {
        LoginUser loginUser = getCurrentLoginUser();
        if (loginUser != null) {
            return Optional.of(loginUser);
        }
        return Optional.empty();
    }


}
